package com.dfbz.demo05_Field;

import org.junit.Test;

import java.lang.reflect.Field;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo02_Field的功能 {
    @Test
    public void test1() throws Exception {
        // 1. 字节码对象
        Class<TestEntity> testEntityClass = TestEntity.class;

        // 2. 根据字段名获取字段
        Field usernameField = testEntityClass.getField("username");


        TestEntity obj = new TestEntity();
        obj.username="123";
        String username = (String) usernameField.get(obj);          // root

        System.out.println(username);
    }


    @Test
    public void test2() throws Exception {
        // 1. 字节码对象
        Class<TestEntity> testEntityClass = TestEntity.class;

        // 2. 根据字段名获取字段
        Field usernameField = testEntityClass.getField("username");

        TestEntity obj = new TestEntity();
        usernameField.set(obj,"zhangsan");

        System.out.println(obj.username);           // ?
    }


    @Test
    public void test3() throws Exception {
        // 1. 字节码对象
        Class<TestEntity> testEntityClass = TestEntity.class;

        // 2. 根据字段名获取字段
        Field passwordField = testEntityClass.getDeclaredField("password");

        // 只要不是public修饰的都加上强制访问
        passwordField.setAccessible(true);

        TestEntity obj = new TestEntity();
        String password = (String) passwordField.get(obj);
        System.out.println(password);
    }



    @Test
    public void test4() throws Exception {
        // 1. 字节码对象
        Class<TestEntity> testEntityClass = TestEntity.class;

        // 2. 根据字段名获取字段
        Field phoneField = testEntityClass.getDeclaredField("phone");
        phoneField.setAccessible(true);

        TestEntity obj = new TestEntity();

        phoneField.set(obj,"119");

        System.out.println(obj.phone);
        System.out.println(phoneField.get(obj));
    }



    @Test
    public void test5() throws Exception {
        // 1. 字节码对象
        Class<TestEntity> testEntityClass = TestEntity.class;

        // 2. 根据字段名获取字段
        Field emailField = testEntityClass.getDeclaredField("email");
        emailField.setAccessible(true);

        TestEntity obj = new TestEntity();

        emailField.set(obj,"root@admin.com");

        System.out.println(emailField.get(obj));                // 反射的弊端: 破坏了类的封装性
    }
}
